<template>

  <popup :title="title" @confirm="handleSubmit" ref="popupRef">

    <el-scrollbar height="500px">
      <el-tree
          :data="menu"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="selectData"
          @check-change="handleCheckChange"
      />
    </el-scrollbar>

  </popup>

</template>

<script setup>
import popup from '@/components/popup/index.vue'
import {onMounted, reactive, ref, shallowRef} from "vue";
import {addMenu, listMenu} from '@/api/role'
import useUserStore from "@/stores/modules/user";

const userStore = useUserStore()
const popupRef = shallowRef(popup)
const emit = defineEmits(['success'])

const title = ref('分配权限')
const formData = reactive({
  role_id: 0,
  menu_ids: {}
})

const menu = ref([])
const selectData = ref([])
const handleCheckChange = (data, checked) => {
  if (checked) {
    formData.menu_ids[data.id] = data.id
  } else {
    delete formData.menu_ids[data.id]
  }
}

const handleSubmit = async () => {
  await addMenu(formData)
  emit('success')
}

const setFormData = async (row) => {
  formData.role_id = row.id
  title.value = '分配【' + row.name + '】的权限'

  await listMenu({role_id: row.id}).then((data) => {

    let selectTempData = []
    data.forEach((item) => {
      selectTempData.push(item.menu_id)
      formData.menu_ids[item.menu_id] = item.menu_id
    })

    selectData.value = selectTempData
  })
}

onMounted(async () => {
  menu.value = userStore.menu
})

defineExpose({
  setFormData
})
</script>

<style scoped>

</style>